﻿using Microsoft.IdentityModel.Tokens;
using ShortLink.Common.Settings;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ShortLink.Common.Jwt
{
    public class JwtHelper
    {
        public static string GetToken(TokenModel model) 
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, model.Username),
                new Claim(ClaimTypes.NameIdentifier, model.AccountNo.ToString()), 
                new Claim(ClaimTypes.Email,model.Mail)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.GetValue("Jwt","SecretKey")));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: AppSettings.GetValue("Jwt","Issuer"),
                audience: AppSettings.GetValue("Jwt","Audience"),
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds
            );
            return new JwtSecurityTokenHandler().WriteToken(token);

        }

        public static TokenModel ParseTokenModel(string token) 
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.UTF8.GetBytes(AppSettings.GetValue("Jwt", "SecretKey"));

                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false, // 这里可以改为 true 并指定 Issuer
                    ValidateAudience = false, // 这里可以改为 true 并指定 Audience
                    ValidateLifetime = false // 是否检查 Token 过期时间
                };

                var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out _);
                return new TokenModel { 
                    AccountNo = int.Parse(principal.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value),
                    Username = principal.Claims.First(x => x.Type == ClaimTypes.Name).Value,
                    Mail = principal.Claims.First(x => x.Type == ClaimTypes.Email).Value,
                };


            }
            catch
            {
                return null;
            }

        }


    }
}
